package com.itheima.service.impl;

import com.itheima.mapper.MemberMapper;
import com.itheima.pojo.Login;
import com.itheima.pojo.Member;
import com.itheima.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MemberMapper memberMapper;


    /**
     * 发送验证码
     * @param telephone
     */
    @Override
    public void sendValidateCode(String telephone) {
        // 生成验证码
        String validateCode = "123456";

        // 保存验证码到 Redis，并设置过期时间为 5 分钟
        String redisKey = "validate_code:" + telephone;
        redisTemplate.opsForValue().set(redisKey, validateCode, 5, TimeUnit.MINUTES);
    }

    @Override
    public String login(Login login) {
        String telephone = login.getTelephone();
        String inputCode = login.getValidateCode();

        String redisKey = "validate_code:" + telephone;
        String validateCode = (String) redisTemplate.opsForValue().get(redisKey);

        //校验验证码
        if (!inputCode.equals(validateCode)) {
            return "验证码输入错误";
        }

        // 验证码正确，检查用户是否为会员
        Member member = memberMapper.findMemberByTelephone();
        if (member == null) {
            // 如果不是会员，自动注册
            LocalDateTime regTime = LocalDateTime.now();
            memberMapper.registerMember(null,null,null,telephone, regTime);
        }

        return "登录成功";
    }

}
